<template>
  <view class="coupons-container">
    <view class="page-header">
      <text class="page-title">会员套餐</text>
      <text class="page-subtitle" v-if="memberTime">您的会员到期时间：{{memberTime}}</text>
      <text class="page-subtitle" v-else>开通VIP会员，享受更多权益</text>
    </view>
    
    <view class="coupons-list">
      <view class="empty-tip" v-if="!couponsList.length">
        <text class="iconfont icon-empty"></text>
        <text>暂无可用套餐</text>
      </view>
      
      <view 
        class="coupon-item" 
        v-for="(item, index) in couponsList" 
        :key="index" 
        :class="{'coupon-selected': selectedCoupon === index}"
        @click="selectCoupon(index)"
      >
        <view class="coupon-item-content">
          <view class="coupon-left">
            <view class="coupon-days">
              <text class="days-num">{{item.daysToAdd}}</text>
              <text class="days-unit">天</text>
            </view>
          </view>
          <view class="coupon-right">
            <view class="coupon-name">{{item.name || '会员套餐'}}</view>
            <view class="coupon-desc">{{item.couponsInfo || '开通VIP会员，享受更多权益'}}</view>
            <view class="coupon-price">
              <text class="price-symbol">¥</text>
              <text class="price-num">{{item.price || 0}}</text>
            </view>
          </view>
          <view class="coupon-check" v-if="selectedCoupon === index">
            <text class="iconfont icon-check"></text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="action-btn">
      <button 
        class="cu-btn block bg-yellow lg" 
        :disabled="selectedCoupon === -1 || !couponsList.length" 
        @click="handlePay"
      >
        立即支付
      </button>
    </view>
    
    <!-- 确认支付弹窗 -->
    <view class="cu-modal" :class="showPayModal?'show':''">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">确认支付</view>
          <view class="action" @click="showPayModal=false">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
        <view class="padding-xl">
          <view class="confirm-payment">
            <view class="package-info" v-if="selectedCoupon !== -1">
              <view class="package-name">{{couponsList[selectedCoupon].name || '会员套餐'}}</view>
              <view class="package-days">{{couponsList[selectedCoupon].daysToAdd}}天</view>
              <view class="package-price">¥{{couponsList[selectedCoupon].price || 0}}</view>
            </view>
            <view class="payment-method">
              <text class="iconfont icon-wechat text-green"></text>
              <text>微信支付</text>
            </view>
            <button class="cu-btn block bg-yellow lg" @click="payWithWechat">确认支付</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { listCoupons } from '@/api/products/coupons'
  import request from '@/utils/request'
  
  export default {
    data() {
      return {
        memberTime: null,
        couponsList: [],
        selectedCoupon: -1,
        showPayModal: false
      }
    },
    created() {
      // 从用户信息中获取会员到期时间
      if (this.$store.state.user.memberTime) {
        this.memberTime = this.$store.state.user.memberTime
      }
      // 获取套餐列表
      this.getCouponsList()
    },
    methods: {
      // 获取套餐列表
      getCouponsList() {
        this.$modal.loading("加载中...")
        listCoupons({couponsStatus: 0}).then(res => {
          this.$modal.closeLoading()
          if (res.code === 200 && res.rows) {
            this.couponsList = res.rows
            console.log(this.couponsList)
            // 默认选中第一个套餐
            if (this.couponsList.length > 0) {
              this.selectedCoupon = 0
            }
          }
        }).catch(err => {
          this.$modal.closeLoading()
          this.$modal.msgError("获取套餐列表失败")
          console.error('获取套餐列表失败', err)
        })
      },
      
      // 选择套餐
      selectCoupon(index) {
        this.selectedCoupon = index
      },
      
      // 处理支付
      handlePay() {
        // 检测iOS设备
        const systemInfo = uni.getSystemInfoSync();
        if (systemInfo.platform === 'ios') {
          this.$modal.msgError("由于相关规范，iOS功能暂不可用");
          return;
        }
        
        if (this.selectedCoupon === -1) {
          this.$modal.msgError("请选择套餐");
          return;
        }
        
        // 获取选中的套餐
        const selectedPackage = this.couponsList[this.selectedCoupon]
        
        // 显示确认支付弹窗
        this.showPayModal = true
        
        console.log('选中套餐:', selectedPackage)
      },
      
      // 微信支付
      payWithWechat() {
        // 检测iOS设备
        const systemInfo = uni.getSystemInfoSync();
        if (systemInfo.platform === 'ios') {
          this.$modal.msgError("由于相关规范，iOS功能暂不可用");
          this.showPayModal = false;
          return;
        }
        
        // 关闭支付弹窗
        this.showPayModal = false
        
        if (this.selectedCoupon === -1) {
          this.$modal.msgError("请选择套餐")
          return;
        }
        
        const selectedPackage = this.couponsList[this.selectedCoupon]
        
        // 显示加载中
        this.$modal.loading("支付处理中...")
        
        // 调用创建订单接口
        this.createOrder(selectedPackage)
      },
      
      // 创建订单
      createOrder(packageInfo) {
        // 构建订单参数
        const orderParams = {
          id: packageInfo.id,
          amount: packageInfo.price,
          days: packageInfo.daysToAdd,
          payType: 'wxpay' // 支付方式：微信支付
        }
        
        // 调用创建订单接口
        request({
          url: '/wx/pay/createOrder',
          method: 'post',
          data: orderParams
        }).then(res => {
          if (res.code === 200) {
            // 关闭加载提示
            this.$modal.closeLoading()
            // 调用微信支付
            this.callWxPay(res.data)
          } else {
            this.$modal.closeLoading()
            this.$modal.msgError(res.msg || "创建订单失败")
          }
        }).catch(err => {
          this.$modal.closeLoading()
          this.$modal.msgError("创建订单失败")
          console.error('创建订单失败', err)
        })
      },
      
      // 调用微信支付
      callWxPay(payInfo) {
        // 检查返回的支付信息
        if (!payInfo) {
          this.$modal.msgError("支付参数错误")
          return
        }
        
        // 调用微信小程序支付API
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: payInfo.timeStamp,
          nonceStr: payInfo.nonceStr,
          package: payInfo.packageStr,
          signType: payInfo.signType,
          paySign: payInfo.paySign,
          success: (res) => {
            console.log('支付成功', res)
            this.$modal.msgSuccess("支付成功")
            // 支付成功后调用支付成功接口并刷新会员信息
            this.notifyPaySuccess(payInfo.orderId)
          },
          fail: (err) => {
            console.log('支付失败', err)
            if (err.errMsg === 'requestPayment:fail cancel') {
              this.$modal.msgInfo("支付已取消")
            } else {
              this.$modal.msgError("支付失败")
            }
          },
          complete: () => {
            console.log('支付完成')
          }
        })
      },
      
      // 通知服务器支付成功
      notifyPaySuccess(orderId) {
        // 调用支付成功接口
        request({
          url: '/wx/pay/paySuccess',
          method: 'get',
          data: { orderId: orderId }
        }).then(res => {
          if (res.code === 200) {
            console.log('支付成功通知已发送')
            // 刷新会员信息
            this.refreshMemberInfo()
          } else {
            this.$modal.msgError(res.msg || "更新支付状态失败")
          }
        }).catch(err => {
          console.error('通知支付成功失败', err)
          // 即使通知失败也尝试刷新会员信息
          this.refreshMemberInfo()
        })
      },
      
      // 刷新会员信息
      refreshMemberInfo() {
        // 更新用户信息，获取新的会员到期时间
        this.$store.dispatch('GetInfo').then(res => {
          // 更新本地会员时间
          if (this.$store.state.user.memberTime) {
            this.memberTime = this.$store.state.user.memberTime
          }
          
          // 延迟后返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f5f6f7;
  }
  
  .coupons-container {
    padding: 20px;
    
    .page-header {
      text-align: center;
      margin-bottom: 30px;
      
      .page-title {
        font-size: 20px;
        font-weight: bold;
        display: block;
        margin-bottom: 10px;
      }
      
      .page-subtitle {
        font-size: 14px;
        color: #666;
      }
    }
    
    .coupons-list {
      .empty-tip {
        text-align: center;
        padding: 40px 0;
        color: #999;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .iconfont {
          font-size: 48px;
          margin-bottom: 10px;
        }
      }
      
      .coupon-item {
        background-color: white;
        border-radius: 8px;
        margin-bottom: 15px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        
        &.coupon-selected {
          border: 2px solid #FFD700;
        }
        
        &:before {
          content: '';
          position: absolute;
          left: -5px;
          top: 50%;
          transform: translateY(-50%);
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background-color: #f5f6f7;
        }
        
        &:after {
          content: '';
          position: absolute;
          right: -5px;
          top: 50%;
          transform: translateY(-50%);
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background-color: #f5f6f7;
        }
        
        .coupon-item-content {
          display: flex;
          padding: 20px;
          
          .coupon-left {
            flex: 0 0 30%;
            display: flex;
            align-items: center;
            justify-content: center;
            border-right: 1px dashed #eee;
            
            .coupon-days {
              text-align: center;
              
              .days-num {
                font-size: 32px;
                font-weight: bold;
                color: #ff6b00;
              }
              
              .days-unit {
                font-size: 14px;
                color: #ff6b00;
              }
            }
          }
          
          .coupon-right {
            flex: 1;
            padding-left: 15px;
            position: relative;
            
            .coupon-name {
              font-size: 16px;
              font-weight: bold;
              margin-bottom: 5px;
            }
            
            .coupon-desc {
              font-size: 12px;
              color: #999;
              margin-bottom: 10px;
            }
            
            .coupon-price {
              .price-symbol {
                font-size: 14px;
                color: #ff6b00;
              }
              
              .price-num {
                font-size: 20px;
                font-weight: bold;
                color: #ff6b00;
              }
            }
          }
          
          .coupon-check {
            position: absolute;
            right: 10px;
            top: 10px;
            width: 20px;
            height: 20px;
            background-color: #FFD700;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .iconfont {
              font-size: 12px;
            }
          }
        }
      }
    }
    
    .action-btn {
      margin-top: 30px;
      
      .cu-btn {
        border-radius: 25px;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .payment-options {
      .payment-option {
        display: flex;
        align-items: center;
        padding: 15px 0;
        
        .iconfont {
          font-size: 24px;
          margin-right: 10px;
        }
      }
    }
    
    .confirm-payment {
      .package-info {
        text-align: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
        
        .package-name {
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .package-days {
          font-size: 14px;
          color: #666;
          margin-bottom: 5px;
        }
        
        .package-price {
          font-size: 24px;
          font-weight: bold;
          color: #ff6b00;
        }
      }
      
      .payment-method {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 20px;
        
        .iconfont {
          font-size: 24px;
          margin-right: 10px;
        }
      }
      
      .cu-btn {
        border-radius: 25px;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
</style> 